package com.programmercarl.array;

import java.util.ArrayList;

/**
 * https://leetcode.cn/problems/fruit-into-baskets/description/
 *
 * @author yulongtian
 * @create 2024-12-11 10:17
 */
public class Test12 {
    public static void main(String[] args) {
//        System.out.println(totalFruit(new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4, 3, 3, 4, 5, 2, 2, 1, 1, 1, 1, 1, 1, 2, 2, 3, 2, 3, 3, 3, 3, 3, 4}));
//        System.out.println(totalFruit(new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4}));
        System.out.println(totalFruit(new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4, 3, 3, 4, 5, 2, 2, 1, 5, 1, 1, 1, 2, 2, 3, 2, 3, 3, 3, 3, 3, 4, 1, 1, 2, 1, 12, 3, 3, 3}));
    }

    /**
     * 双指针模拟滑动窗口
     *
     * @param fruits
     * @return
     */
    public static int totalFruit(int[] fruits) {
        int res = 0;
        int slowPointer = 0;
        int fastPointer = 0;
        ArrayList<Integer> bucket = new ArrayList<>(2);
        bucket.add(-1);
        bucket.add(-1);
        int[] count = new int[]{0, 0};
        for (; fastPointer < fruits.length; ) {
            while (fastPointer < fruits.length && bucket.contains(fruits[fastPointer])) {
                int index = bucket.indexOf(fruits[fastPointer]);
                count[index]++;
                fastPointer++;
                res = Math.max(res, fastPointer - slowPointer);
            }
            if (fastPointer < fruits.length && bucket.get(0) == -1) {//篮子都是空的，先放第一个篮子里
                bucket.set(0, fruits[fastPointer]);
                count[0]++;
                fastPointer++;
                res = Math.max(res, fastPointer - slowPointer);
                continue;
            } else if (fastPointer < fruits.length && bucket.get(1) == -1) {//第二个篮子为空，放第二个篮子里
                bucket.set(1, fruits[fastPointer]);
                count[1]++;
                fastPointer++;
                res = Math.max(res, fastPointer - slowPointer);
                continue;
            }
            // 有新的水果
            int index = -1;//需要移除的水果篮子的索引
            while (slowPointer < fastPointer) {
                if (count[0] == 0) {
                    // 篮子里要移除0
                    index = 0;
                    break;
                }
                if (count[1] == 0) {
                    // 篮子里要移除1
                    index = 1;
                    break;
                }
                int temp_index = bucket.indexOf(fruits[slowPointer]);
                count[temp_index]--;
                slowPointer++;
            }
            if (fastPointer < fruits.length) {
                bucket.set(index, fruits[fastPointer]);
                count[index]++;
                fastPointer++;
                res = Math.max(res, fastPointer - slowPointer);
            }
        }
        return res;
    }

}
